import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoSever {
    private DatagramSocket socket = null;

    public UdpEchoSever(int port) throws SocketException {
        this.socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");

        while(true){

            DatagramPacket requestParcket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestParcket);
            String request = new String(requestParcket.getData(), 0, requestParcket.getLength());
            String reponse = process(request);
            DatagramPacket responsePacket = new DatagramPacket(reponse.getBytes(), reponse.getBytes().length,
                    // requestPacket 是从客户端这里收来的. getSocketAddress 就会得到客户端的 ip 和 端口
                    requestParcket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req: %s, resp: %s\n", requestParcket.getAddress().toString(),
                    requestParcket.getPort(), request, reponse);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoSever udpEchoSever = new UdpEchoSever(9090);
        udpEchoSever.start();
    }
}